<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>找出字符串中第一个匹配项的下标</title>
</head>

<body>
  <script>
    // var strStr = function (haystack, needle) {
    //   const n = haystack.length, m = needle.length;
    //   for (let i = 0; i + m <= n; i++) {
    //     let flag = true;
    //     for (let j = 0; j < m; j++) {
    //       if (haystack[i + j] != needle[j]) {
    //         flag = false;
    //         break;
    //       }
    //     }
    //     if (flag) {
    //       return i;
    //     }
    //   }
    //   return -1;
    // };


    // 运用includes API 判断是否包含 包含利用indexOf的返回值是当前元素的索引，不包含返回 - 1就行了
    var strStr = function (haystack, needle) {
      return haystack.includes(needle) ? haystack.indexOf(needle) : -1
    };
    console.log(strStr("sadbutsad", "sad"))
  </script>
</body>

</html>